package com.apes.fn.controlling.vehicle.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.business.fixedLoss.modle.LossQuotation;
import com.apes.fn.business.fixedLoss.repository.LossQuotationRepository;
import com.apes.fn.controlling.vehicle.model.VehicleInfo;
import com.apes.fn.controlling.vehicle.repository.VehicleInfoRepository;
import com.apes.fn.server.pickUpCar.repository.PickUpCarRepository;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.express.FuncAlias;
import com.apes.framework.util.MapUtil;
import com.apestech.framework.json.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;


/**
 * Creator: zouyc
 * CreateDate: 2021-03-19 9:25
 * Description:
 **/
@Service("vehicleForFunService")
public class VehicleForFunService extends abstractVehicleinfo{

    //基于构造方法，注入
    private final VehicleInfoRepository repository;
    public VehicleForFunService(VehicleInfoRepository repository) {
        this.repository = repository;
    }

    @FuncAlias(name = "存在接车")
    public boolean isPickCar(String id){
        VehicleInfo vehicleInfo = repository.findOne(id);
        return carState(obtainCarData(vehicleInfo.getDept().getId(),vehicleInfo.getFnCustomerExpand().getId())); //接车状态
    }

    @FuncAlias(name = "存在内协接车")
    public boolean isInnerPickDelUpCar(String id){
        VehicleInfo vehicleInfo = repository.findOne(id);
        return carState(obtainInnerPickDelUpCarData(vehicleInfo.getDept().getId(),vehicleInfo.getFnCustomerExpand().getId())); //内协接车状态
    }

    @FuncAlias(name = "存在终止方案")
    public boolean isEndServicePlan(String id){
        JSONObject planState = getPlanState(id);
        return planState == null ? false : planState.getBoolean("haveEndServicePlan");
    }

    @FuncAlias(name = "存在已领用方案")
    public boolean isServicePlanPick(String id){
        JSONObject planState = getPlanState(id);
        return planState == null ? false : planState.getBoolean("haveServicePlanPick");
    }

    @FuncAlias(name = "存在未结束接车")
    public boolean isPickCarNotEnd(String id){
        return isPickCar(id) || isInnerPickDelUpCar(id);
    }

    @FuncAlias(name = "存在施工")
    public boolean isWorkData(String id){
        JSONObject planState = getPlanState(id);
        return planState == null ? false : planState.getBoolean("haveWaitWork");
    }

    @FuncAlias(name = "是待施工")
    public boolean isWaitWork(String id){
        JSONObject planState = getPlanState(id);
        return planState == null ? false : planState.getBoolean("isWaitWork");
    }

    @FuncAlias(name = "存在锁定单")
    public boolean isLockData(String id){
        JSONObject planState = getPlanState(id);
        return planState == null ? false : planState.getBoolean("haveLock");
    }

    @FuncAlias(name = "存在待质检单")
    public boolean isQualityData(String id){
        JSONObject planState = getPlanState(id);
        return planState == null ? false : planState.getBoolean("haveWaitTest");
    }

    @FuncAlias(name = "存在待结算单")
    public boolean isWaitReciData(String id){
        JSONObject planState = getPlanState(id);
        return planState == null ? false : planState.getBoolean("haveWaitMoney");
    }

    @FuncAlias(name = "存在无工单方案")
    public boolean isHavePlanNoOrder(String id){
        JSONObject planState = getPlanState(id);
        return planState == null ? false : planState.getBoolean("allPart");
    }

    @FuncAlias(name = "存在完工未领料")
    public boolean isFinishWorkNoReceive(String id){
        JSONObject planState = getPlanState(id);
        return planState == null ? false : planState.getBoolean("FinishWorkNoReceive");
    }



    /**
     * 定义：根据门店和车子，找到接车单的创建日期，如果有比这个收款日期更后面的单据，则为有
     * @param id
     * @return
     */
    @FuncAlias(name = "有已结算单")
    public boolean isReciData(String id){
        VehicleInfo vehicleInfo = repository.findOne(id);
        JSONObject json = new JSONObject();
        json.put("DEPT_ID",vehicleInfo.getDept().getId());
        json.put("FN_CUSTOMER_EXPAND_ID",vehicleInfo.getFnCustomerExpand().getId());
        return isHaveReci(json);
    }

    @FuncAlias(name = "内协状态")
    public String innerPickCarState(String id){
        String state = "Z"; //默认是不在任何状态内

        VehicleInfo vehicleInfo = repository.findOne(id);
        JSONObject json = new JSONObject();
        json.put("BELONG_DEPT_ID",vehicleInfo.getDept().getId());
        json.put("FN_CUSTOMER_EXPAND_ID",vehicleInfo.getFnCustomerExpand().getId());
        json.put("PICK_UP_CARS",vehicleInfo.getPickUpCar());


        String result = Optional.ofNullable(obtainInnerPickCar(json)).orElseGet(()->"Z");


        return result.equals("create") ? "A" :
                result.equals("get") ?  "B" :
                        result.equals("return") ? "C" :
                                (result.equals("confirm") || result.equals("repeal")) ? "Z" : "N";
    }

    @FuncAlias(name = "待出方案")
    public boolean settlementStillCar(String id){
        // (存在未结束接车(单号) || ( 存在未结束接车(单号) && 存在终止方案(单号) ))
        return (isPickCarNotEnd(id) || (isPickCarNotEnd(id) && isEndServicePlan(id) ));
    }

    @FuncAlias(name = "待排位")
    public boolean pendingConstruction(String id){
        //   (  存在锁定单(单号) || 是待施工(单号)  || (存在无工单方案(单号) && ! 存在已领用方案(单号)) )
        return (  isLockData(id) || isWaitWork(id)  || (isHavePlanNoOrder(id) && ! isServicePlanPick(id)) );
    }

    @FuncAlias(name = "施工中")
    public boolean underConstruction(String id){
        // 存在施工(单号)
        return isWorkData(id);
    }

    @FuncAlias(name = "待总检")
    public boolean pendingQuality(String id){
        // 存在待质检单(单号)
        return isQualityData(id);
    }

    @FuncAlias(name = "待结算")
    public boolean pendingReceivables(String id){
        // 存在待结算单(单号)  &&  ! 存在完工未领料(单号)
        return isWaitReciData(id)  &&  ! isFinishWorkNoReceive(id);
    }

    @FuncAlias(name = "待交车")
    public boolean pendingStillCar(String id){
        // 存在未结束接车(单号) && 有已结算单(单号)
        return isPickCarNotEnd(id) && isReciData(id);
    }

    /**
     * 传入方案，获取方案状态
     * @param id
     * @return
     */
    private JSONObject getPlanState(String id) {
        VehicleInfo vehicleInfo = repository.findOne(id);
        String fnId = vehicleInfo.getFnCustomerExpand().getId();
        String deptId = vehicleInfo.getDept().getId();
        return planStateForNew(obtainPlanData(deptId,fnId));
    }

    public String obtainResult(SimpleRequest re){
        String id = Optional.ofNullable(re.getJO().getString("id")).orElseThrow(()->new RuntimeException("请传入正确格式"));
        List list = new ArrayList();
        //存在接车
        list.add(MapUtil.mapper("函数名","存在接车","返回结果",isPickCar(id)));
        //存在施工
        list.add(MapUtil.mapper("函数名","存在施工","返回结果",isWorkData(id)));
        //存在锁定单
        list.add(MapUtil.mapper("函数名","存在锁定单","返回结果",isLockData(id)));
        //存在质检单
        list.add(MapUtil.mapper("函数名","存在质检单","返回结果",isQualityData(id)));
        //存在待结算单
        list.add(MapUtil.mapper("函数名","存在待结算单","返回结果",isWaitReciData(id)));
        //有已结算单
        list.add(MapUtil.mapper("函数名","有已结算单","返回结果",isReciData(id)));
        //内协状态
        list.add(MapUtil.mapper("函数名","内协状态","返回结果",innerPickCarState(id)));
        //存在定损
        list.add(MapUtil.mapper("函数名","存在定损","返回结果",existLossQuotation(id)));

        //存在无工单方案
        list.add(MapUtil.mapper("函数名","存在无工单方案","返回结果",isHavePlanNoOrder(id)));


        //存在完工未领料
        list.add(MapUtil.mapper("函数名","存在完工未领料","返回结果",isFinishWorkNoReceive(id)));

        String str = null;
        try {
            str = JSON.toJSONString(list);
        }catch (Exception e){
            throw new RuntimeException("格式化错误");
        }
        return str;
    }

    @FuncAlias(name = "存在定损")
    public boolean existLossQuotation(String id){
        VehicleInfo vehicleInfo = repository.findOne(id);
        if(!StringUtils.isEmpty(vehicleInfo.getPickUpCar())){
            List<LossQuotation> quotationList = SpringManager.getBean(LossQuotationRepository.class).findAll(
                    JpaDsl.toCriteriaByEq("customerExpand", vehicleInfo.getFnCustomerExpand())
            );
            if (quotationList.size() == 0){
                return false;
            }else {
                // anyMatch() 断言函数,肯定满足条件, 不满足返回false
                return quotationList.stream().anyMatch(item -> {
                    return !Objects.equals("businessAudit", item.getState())
                            && !Objects.equals("repeal", item.getState()) ;
                });
            }
        }
        return false;
    }

}
